原因: 欄位使用int、string等的類型, 無法保護它不受不正確的賦值和非法的等同性比較
解法: 把欄位的類型宣告為類別, 從而限制賦值和同等性比較
假設有個SystemPermission
類別, 裡面有定義權限的常數REQUESTED
, CLAIMED
, DENIED
與GRANTED
而有一個_state
欄位儲存目前的權限值. 並提供Claimed()
, Denied()
與Granted()
函數做權限值的改變.
public class SystemPermission
{
private bool _granted;
private string _state;
public static readonly string REQUESTED = "REQUESTED";
public static readonly string CLAIMED = "CLAIMED";
public static readonly string DENIED = "DENIED";
public static readonly string GRANTED = "GRANTED";
public string State
{
get => _state;
private set => _state = value;
}
public SystemPermission()
{
State = REQUESTED;
_granted = false;
}
public void Claimed()
{
if (State == REQUESTED)
{
State = CLAIMED;
}
}
public void Denied()
{
if (State == CLAIMED)
{
State = DENIED;
}
}
public void Granted()
{
if (State != CLAIMED)
{
return;
}
State = GRANTED;
_granted = true;
}
public bool IsGranted()
{
return _granted;
}
}
將前面的權限常數, 轉成PermissionState
類別
static readonly
name
字串而SystemPermission
的_state
欄位從字串改成PermissionState
物件.
後續的比較以reference object的比較.
public class PermissionState
{
private readonly string _name;
public PermissionState(string name)
{
_name = name;
}
public override string ToString()
{
return _name;
}
public static readonly PermissionState REQUESTED = new PermissionState("REQUESTED");
public static readonly PermissionState CLAIMED = new PermissionState("CLAIMED");
public static readonly PermissionState DENIED = new PermissionState("DENIED");
public static readonly PermissionState GRANTED = new PermissionState("GRANTED");
}
public class SystemPermission
{
private bool _granted;
public PermissionState State
{
get => _permission;
}
private PermissionState Permission
{
set => _permission = value;
}
private PermissionState _permission;
public SystemPermission()
{
Permission = PermissionState.REQUESTED;
_granted = false;
}
public void Claimed()
{
if (State == PermissionState.REQUESTED)
{
Permission = PermissionState.CLAIMED;
}
}
public void Denied()
{
if (State == PermissionState.CLAIMED)
{
Permission = PermissionState.DENIED;
}
}
public void Granted()
{
if (State != PermissionState.CLAIMED)
{
return;
}
Permission = PermissionState.GRANTED;
_granted = true;
}
public bool IsGranted()
{
return _granted;
}
}